/*
 * @(#)GsMngAction.java
 * 2011-8-21 下午10:40:10
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.gsmng.common.web;


import com.qyxx.jwp.bean.Item;
import com.qyxx.jwp.bean.ModuleProperties;
import com.qyxx.jwp.datasource.TableEntity;
import com.qyxx.jwp.datasource.TeAttr;
import com.qyxx.platform.common.json.JsonOutput;
import com.qyxx.platform.common.module.web.CrudActionSupport;
import com.qyxx.platform.common.module.web.FormatMessage;
import com.qyxx.platform.common.module.web.ValidateMsg;
import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.encode.JsonBinder;
import com.qyxx.platform.common.utils.spring.SpringContextHolder;
import com.qyxx.platform.common.utils.web.ServletUtils;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.gsc.cache.TableEntityCache;
import com.qyxx.platform.gsc.utils.SystemParam;
import com.qyxx.platform.gsmng.common.service.DataShareConfigManager;
import com.qyxx.platform.gsmng.common.service.GsMngManager;
import com.qyxx.platform.gsmng.common.service.ProcManager;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.accountmng.service.AccountManager;
import com.qyxx.platform.sysmng.exception.GsException;
import com.qyxx.platform.sysmng.utils.Constants;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  业务管理通用Action
 *  @author gxj
 *  @version 1.0
 *  @since 1.6 2011-8-21 下午10:40:10
 */
@Namespace("/gs")
@Results({
		@Result(name = CrudActionSupport.SUCCESS, location = "/WEB-INF/content/gs/${moduleName}/${objectName}-list.jsp"),
		@Result(name = "listJs", location = "/WEB-INF/content/gs/${moduleName}/${objectName}-list-js.jsp"),
		@Result(name = CrudActionSupport.ADD, location = "/WEB-INF/content/gs/${moduleName}/${objectName}-view.jsp"),
		@Result(name = CrudActionSupport.EDIT, location = "/WEB-INF/content/gs/${moduleName}/${objectName}-view.jsp"),
		@Result(name = CrudActionSupport.VIEW, location = "/WEB-INF/content/gs/${moduleName}/${objectName}-view.jsp"),
		@Result(name = "viewJs", location = "/WEB-INF/content/gs/${moduleName}/${objectName}-view-js.jsp"),
		@Result(name = CrudActionSupport.VIEW_SUB, location = "/WEB-INF/content/gs/${moduleName}/${objectName}-sub.jsp"),
		@Result(name = GsMngAction.FORMS, location = "/WEB-INF/content/gs/forms/${formName}.jsp"),
		@Result(name = "formJs", location = "/WEB-INF/content/gs/forms/${formName}-js.jsp"),
		@Result(name = GsMngAction.DICTS, location = "/WEB-INF/content/sys/dicts/dicts.jsp"),
		@Result(name = "win", location = "/WEB-INF/content/sys/dataFilter/win-datagrid.jsp"),
		@Result(name = "usersWin", location = "/WEB-INF/content/sys/sendMessage/message.jsp"),
		@Result(name = "file", location = "/WEB-INF/content/sys/importExcel/import-file.jsp"),
		@Result(name = "dataWin", location = "/WEB-INF/content/sys/dataWin/set-data.jsp")
		})
public class GsMngAction extends CrudActionSupport<Map<String, Object>>{
	
	/**
	 * long
	 */
	private static final long serialVersionUID = -5510643301783150855L;
	
	/**
	 * 数据字典
	 */
	public static final String DICTS = "dicts";
	/**
	 * 自定表单
	 */
	public static final String FORMS = "forms";
	/**
	 * 模块数据源
	 */
	public static final String MODULE_DS = "module";

	/* 实体名（模块名.实体对象名） */
	protected String entityName;
	
	/* 模块名 */
	protected String moduleName;
	
	/* 实体对象名 */
	protected String objectName;
	
	/* 自定义表单名 */
	protected String formName;
	/* Json格式数据 */
	protected String jsonSaveData;
	
	protected String jsonSenddata;
	/* 查询类型-上一条、下一条、第一条、最后一条 */
	protected String findType;
	
	private GsMngManager gsMngManager;
	
	//判断参数
	private Boolean appendFlag = true;
	
	//操作方法
	private String operMethod = CrudActionSupport.VIEW;
	
	//关联附件ID
	private Long attachId;
	
	private AccountManager accountManager;
	
	private DataShareConfigManager dataShareConfigManager;
	
	private JsonBinder jsonBinder = JsonBinder.getAlwaysMapper();
	
	private SystemParam systemParam = SpringContextHolder.getBean("systemParam");
	
	private String field;
	
	private String value;
	
	private String style;
	
	private ProcManager  procManager;
	
	private String procContent;
	
	private String procKey;
	
	private Long[] entityIds;
	
	private File filedata;
	
	private String relevanceModule;
	
	public String getRelevanceModule() {
		return relevanceModule;
	}
	public void setRelevanceModule(String relevanceModule) {
		this.relevanceModule = relevanceModule;
	}
	public File getFiledata() {
		return filedata;
	}
	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}
	public Long[] getEntityIds() {
		return entityIds;
	}

	
	public void setEntityIds(Long[] entityIds) {
		this.entityIds = entityIds;
	}

	public String getProcKey() {
		return procKey;
	}
	
	public void setProcKey(String procKey) {
		this.procKey = procKey;
	}


	public String getProcContent() {
		return procContent;
	}

	public void setProcContent(String procContent) {
		this.procContent = procContent;
	}

	public ProcManager getProcManager() {
		return procManager;
	}

	public void setProcManager(ProcManager procManager) {
		this.procManager = procManager;
	}


	public String getStyle() {
		return style;
	}


	public void setStyle(String style) {
		this.style = style;
	}

	/**
	 * @return systemParam
	 */
	public SystemParam getSystemParam() {
		return systemParam;
	}
	
	/**
	 * @param systemParam
	 */
	public void setSystemParam(SystemParam systemParam) {
		this.systemParam = systemParam;
	}
	
	public String getField() {
		return field;
	}
	
	public void setField(String field) {
		this.field = field;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	/**
	 * @return accountManager
	 */
	public AccountManager getAccountManager() {
		return accountManager;
	}
	
	/**
	 * @param accountManager
	 */
	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	/**
	 * @param dataShareConfigManager
	 */
	@Autowired
	public void setDataShareConfigManager(
			DataShareConfigManager dataShareConfigManager) {
		this.dataShareConfigManager = dataShareConfigManager;
	}
	/**
	 * @return operMethod
	 */
	public String getOperMethod() {
		return operMethod;
	}
	
	/**
	 * @param operMethod
	 */
	public void setOperMethod(String operMethod) {
		this.operMethod = operMethod;
	}
	/**
	 * @return entityName
	 */
	public final String getEntityName() {
		return entityName;
	}
	
	/**
	 * @param entityName
	 */
	public void setEntityName(String entityName) {
		this.entityName = entityName;
		//解析为模块名与实体对象名
		if(StringUtils.isNotBlank(entityName)) {
			String[] astr = StringUtils.split(StringUtils.lowerCase(entityName), ".");
			if(astr.length >= 2) {
				if(this.moduleName==null) this.moduleName = astr[0];
				if(this.objectName==null) this.objectName = astr[1];
			} else {
				throw new GsException("请求参数错误，请检查");
			}
		} else {
			throw new GsException("请求参数错误，请检查");
		}
	}

	
	/**
	 * @return moduleName
	 */
	public String getModuleName() {
		return moduleName;
	}

	
	/**
	 * @param moduleName
	 */
	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	
	/**
	 * @return objectName
	 */
	public String getObjectName() {
		return objectName;
	}

	
	/**
	 * @param objectName
	 */
	public void setObjectName(String objectName) {
		this.objectName = objectName;
	}

	
	
	public String getFormName() {
		return formName;
	}
	
	public void setFormName(String formName) {
		this.formName = formName;
	}
	/**
	 * @return jsonSaveData
	 */
	public String getJsonSaveData() {
		return jsonSaveData;
	}

	
	/**
	 * @param jsonSaveData
	 */
	public void setJsonSaveData(String jsonSaveData) {
		this.jsonSaveData = jsonSaveData;
	}
		
	public String getJsonSenddata() {
		return jsonSenddata;
	}
	
	public void setJsonSenddata(String jsonSenddata) {
		this.jsonSenddata = jsonSenddata;
	}


	/**
	 * @return the findType
	 */
	public String getFindType() {
		return findType;
	}
	
	/**
	 * @param findType the findType to set
	 */
	public void setFindType(String findType) {
		this.findType = findType;
	}
	/**
	 * @return the appendFlag
	 */
	public Boolean getAppendFlag() {
		return appendFlag;
	}
	/**
	 * @param appendFlag the appendFlag to set
	 */
	public void setAppendFlag(Boolean appendFlag) {
		this.appendFlag = appendFlag;
	}
	/**
	 * @param gsMngManager
	 */
	@Autowired
	public void setGsMngManager(GsMngManager gsMngManager) {
		this.gsMngManager = gsMngManager;
	}

	
	/**
	 * @return attachId
	 */
	public Long getAttachId() {
		return attachId;
	}
	
	/**
	 * @param attachId
	 */
	public void setAttachId(Long attachId) {
		this.attachId = attachId;
	}
	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		return SUCCESS;
	}

	/**
	 * 修正entityName
	 * 
	 * @return
	 * @throws Exception
	 */
	private void changeEntityName() {
		if(StringUtils.isNotBlank(relevanceModule)) {
			entityName = relevanceModule.split("\\.")[1].toLowerCase() + com.qyxx.platform.gsc.utils.Constants.NAME_SPLIT_SYMBOL + entityName.split("\\.")[1];
		}
	}
	
	/**
	 * 设置关联模块过滤
	 * 
	 * @return
	 * @throws Exception
	 */
	private void filterRelevanceModul(List<PropertyFilter> filters) {
		if(StringUtils.isNotBlank(relevanceModule)) {
			PropertyFilter p = new PropertyFilter("EQS_relevanceModule", entityName);
			filters.add(p);
		}
	}
	
	/**
	 * 查询列表Json
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryList() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		checkDataAuth(user, filters);
		filterRelevanceModul(filters);
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		//过滤子列表属性
		TableEntity te = TableEntityCache.getInstance().get(entityName);
		if(te.getIsReferCommon()) {
			//关联表查询
			pager = gsMngManager.searchEntityByHql(pager, filters);
		} else {
			pager = gsMngManager.searchEntity(pager, filters);
		}
		/*if(null!=te) {
			if(te.getIsSubEntity()) {
				//子实体
				List<String> filterProp = Lists.newArrayList();
				filterProp.add(te.getRefEntityName());
				preHandleObject(pager, filterProp);
			} else {
				//主实体
				if(null!=te.getSubEntitys() && !te.getSubEntitys().isEmpty()) {
					List<String> filterProp = Lists.newArrayList();
					for(TableEntity t : te.getSubEntitys()) {
						filterProp.add(t.getRefSubEntityName());
					}
					preHandleObject(pager, filterProp);
				}
			}
		}*/
		Struts2Utils.renderJson(pager);
		return null;
	}	
	/**
	 * 查询自定义表单页面Json
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryFormList() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		List<PropertyFilter> fixFilters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest(), "fix");
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		gsMngManager.setEntityName(entityName);
		//过滤子列表属性
		pager = gsMngManager.searchEntityByHql(pager, filters, fixFilters);

		Struts2Utils.renderJson(pager);
		return null;
	}	
	/**
	 * 数据字典查询列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryDictList() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		//User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		//checkDataAuth(user, filters);
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		gsMngManager.setEntityName(entityName);
		pager = gsMngManager.searchEntity(pager, filters);
		
		//过滤子列表属性
		/*TableEntity te = TableEntityCache.getInstance().get(entityName);
		if(null!=te) {
			if(te.getIsSubEntity()) {
				//子实体
				List<String> filterProp = Lists.newArrayList();
				filterProp.add(te.getRefEntityName());
				preHandleObject(pager, filterProp);
			} else {
				//主实体
				if(null!=te.getSubEntitys() && !te.getSubEntitys().isEmpty()) {
					List<String> filterProp = Lists.newArrayList();
					for(TableEntity t : te.getSubEntitys()) {
						filterProp.add(t.getRefSubEntityName());
					}
					preHandleObject(pager, filterProp);
				}
			}
		} else {
			throw new GsException("查询实体" + entityName + "不存在");
		}*/
		Struts2Utils.renderJson(pager);
		return null;
	}
	
	/**
	 * 查询子列表Json
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String querySubList() throws Exception {
		TableEntity te = TableEntityCache.getInstance().get(entityName);
		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		gsMngManager.setEntityName(entityName);
		pager.setPageSize(Integer.MAX_VALUE);
		if(te.getIsReferCommon()) {
			//关联表查询
			PropertyFilter pf = new PropertyFilter("EQL_masterId", String.valueOf(id));
			filters.add(pf);
			pager = gsMngManager.searchEntityByHql(pager, filters);
		} else {
			PropertyFilter pf = new PropertyFilter("EQL_" + te.getRefEntityName() + ".id", String.valueOf(id));
			filters.add(pf);
			pager = gsMngManager.searchEntity(pager, filters);
		}
		
		//过滤子列表属性
		/*if(te.getIsSubEntity()) {
			//子实体
			List<String> filterProp = Lists.newArrayList();
			filterProp.add(te.getRefEntityName());
			preHandleObject(pager, filterProp);
		}*/
		Struts2Utils.renderJson(pager);
		return null;
	}
	
	/**
	 * 查询实体对象Json
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryEntity() throws Exception {
		changeEntityName();
		//过滤子列表属性
		TableEntity te = TableEntityCache.getInstance().get(entityName);
		if (id != null) {
			User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
			gsMngManager.setUser(user);
			gsMngManager.setEntityName(entityName);
			if(te.getIsReferCommon()) {
				//关联表
				entity = gsMngManager.getEntityByHql(id);
			} else {
				entity = gsMngManager.getEntity(id);
			}
		} else {
			entity = new HashMap<String, Object>();
		}
		
		/*if(null!=te && null!=te.getSubEntitys() && !te.getSubEntitys().isEmpty()) {
			List<String> filterProp = Lists.newArrayList();
			for(TableEntity t : te.getSubEntitys()) {
				filterProp.add(t.getRefSubEntityName());
			}
			preHandleObject(entity, filterProp);
		}*/
		
		formatMessage.setMsg(entity);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}	
	
	@JsonOutput
	@Override
	public String input() throws Exception {
		List<String> urls = new ArrayList<String>();
		//urls.add("E:/javasoft/jiawasoft/jiawasoft-gsweb/src/ContractsHead.hbm.xml");
		//urls.add("E:/javasoft/jiawasoft/jiawasoft-gsweb/src/ContractsSheet.hbm.xml");
//		HibernateUtils.updateHibernateCfg(urls);
//		urls = new ArrayList<String>();
/*		urls.add("E:/05-Product/03-ERP/Source/MainEntity1.hbm.xml");
		urls.add("E:/05-Product/03-ERP/Source/SubEntity1.hbm.xml");
		HibernateUtils.updateHibernateCfg(urls);*/
		
		//GsParseUtils.handleGs(Struts2Utils.getAppRealPath(), new File("E:/upload/Config.zip"));
		formatMessage.setMsg("动态加载hbm配置文件成功");
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 跳转到新增页面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String add() throws Exception {
		operMethod = CrudActionSupport.ADD;
		return ADD;
	}
	
	/**
	 * 跳转到修改页面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		operMethod = CrudActionSupport.EDIT;
		return EDIT;
	}

	@SuppressWarnings("unchecked")
	@JsonOutput
	@Override
	public String save() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		Map<String, Object> map = jsonBinder.fromJson(jsonSaveData, HashMap.class);
		Map<String, Object> mapSend = jsonBinder.fromJson(jsonSenddata, HashMap.class);
		if(!StringUtils.isBlank(relevanceModule)) {
			map.put("relevanceModule", entityName);
		}
		changeEntityName();
		gsMngManager.setUser(user);
		gsMngManager.setEntityName(entityName);
		gsMngManager.saveEntity(map,mapSend);
		id=(Long)map.get(GsMngManager.ID);
		formatMessage.setMsg(gsMngManager.getEntity(id));//重新查下数据，省得客户端再网络请求1次
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 保存子表数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@JsonOutput
	public String saveEntity() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		gsMngManager.setEntityName(entityName);
		Map<String, Object> map = jsonBinder.fromJson(jsonSaveData, HashMap.class);
		gsMngManager.saveSubEntity(map);
		id=((Number)map.get(GsMngManager.ID)).longValue();
		formatMessage.setMsg(id);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 覆盖更新子表数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@JsonOutput
	public String saveReplaceEntity() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		gsMngManager.setEntityName(entityName);
		Map<String, Object> map = jsonBinder.fromJson(jsonSaveData, HashMap.class);
		gsMngManager.saveReplaceSubEntity(map);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 批量保存数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@JsonOutput
	public String saveList() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		List<Map<String, Object>> list = jsonBinder.fromJson(jsonSaveData, ArrayList.class);
		boolean isUpdate = "true".equals(value);
		List<Object> result = gsMngManager.saveEntityList(list, field, isUpdate);
		formatMessage.setMsg(result);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@Override
	public String view() throws Exception {
		operMethod = CrudActionSupport.VIEW;
		return VIEW;
	}


	@JsonOutput
	@Override
	public String delete() throws Exception {
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		if( null!=ids&&ids.length>0  ){
			gsMngManager.deleteEntity(ids);
		}else if(null!=idsStr&& idsStr.length()>0 ){
            String[]  s  = idsStr.split(",");
            Long[]  l = new Long[s.length];
            for(int i=0;i<s.length;i++){
                l[i]=Long.parseLong(s[i]);
            }
			gsMngManager.deleteEntity(l);
		}
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}


	@Override
	protected void prepareModel() throws Exception {
		/*try {
			if (id != null) {
				gsMngManager.setEntityName(entityName);
				entity = gsMngManager.getEntity(id);
			} else {
				entity = new HashMap<String, Object>();
			}	
		} catch(Exception e) {
			logger.error("", e);
		}*/
	}
	
	/**
	 * 数据源获取单列数据
	 * 
	 * @return
	 * @throws Exception
	 */
	/*@JsonOutput
	public String queryValue() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		if(MODULE_DS.equals(style)) {
			List<Map<String, Object>> list = gsMngManager.queryHqlValue(entityName, jsonSaveData);
			Struts2Utils.renderJson(list);
		} else {
			List<Map<String, Object>> list = gsMngManager.queryValue(entityName, jsonSaveData);
			Struts2Utils.renderJson(list);
		}
		return null;
	}*/
	
	/**
	 * 数据源获取映射关系
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String getItems() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<Item> list = gsMngManager.getItems(entityName);
		Struts2Utils.renderJson(list);
		return null;
	}
	
	/**
	 * 数据源分页获取条件查询数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String filterResult() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		
		if(MODULE_DS.equals(style)) {
			List<Map<String, Object>> list = gsMngManager.queryHqlList(entityName, filters, appendFlag, "", page, true);
			formatMessage.setMsg(list);
		} else {
			List<Map<String, Object>> list = gsMngManager.queryList(entityName, filters, appendFlag, "", page, true);
			formatMessage.setMsg(list);
		}
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 数据源获取数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryResult() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		if(MODULE_DS.equals(style)) {
			List<Map<String, Object>> list = gsMngManager.queryHqlList(entityName, filters, appendFlag);
			formatMessage.setMsg(list);
		} else {
			List<Map<String, Object>> list = gsMngManager.queryList(entityName, filters, appendFlag);
			formatMessage.setMsg(list);
		}
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 根据filter参数过滤数据
	 * 用于分页查询数据，dialoguewindow控件使用
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryFilterResult() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		List<PropertyFilter> fixFilters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest(), "fix");
		if(MODULE_DS.equals(style)) {
			Page<Map<String, Object>> p = gsMngManager.queryHqlPageByFilter(entityName, filters, fixFilters, appendFlag, pager);
			Struts2Utils.renderJson(p);
		} else {
			Page<Map<String, Object>> p = gsMngManager.querySqlPageByFilter(entityName, filters, fixFilters, appendFlag, pager);
			Struts2Utils.renderJson(p);
		}
		return null;
	}
	
	/**
	 * 根据q参数过滤数据
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryAjaxResult() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		String q = Struts2Utils.getParameter("q");
		boolean isKeyQuery = Constants.ENABLED.equals(Struts2Utils.getParameter("kq"));//是否精确key查询
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		List<PropertyFilter> fixFilters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest(), "fix");
		filters.addAll(fixFilters);
		List<Map<String, Object>> list = null;
		int queryRows = isKeyQuery?Integer.MAX_VALUE:rows;
		if(MODULE_DS.equals(style)) {
			list = gsMngManager.queryHqlList(entityName, filters, appendFlag, q, queryRows, !isKeyQuery);
			//formatMessage.setMsg(list);
		} else {
			list = gsMngManager.queryList(entityName, filters, appendFlag, q, queryRows, !isKeyQuery);
			//formatMessage.setMsg(list);
		}
		Struts2Utils.renderJson(list);
		return null;
	}
	
	/**
	 * 根据q参数（key值）查询数据集
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryAjaxResultByKey() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		String q = Struts2Utils.getParameter("q");
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		List<Map<String, Object>> list = null;
		if(MODULE_DS.equals(style)) {
			list = gsMngManager.queryHqlList(entityName, filters, true, q, Integer.MAX_VALUE, false);
		} else {
			list = gsMngManager.queryList(entityName, filters, true, q, Integer.MAX_VALUE, false);
		}
		Struts2Utils.renderJson(list);
		return null;
	}
	
	/**
	 * 查询实体对象Json
	 * 查询上一条、下一条、第一条、最后一条
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryEntityByType() throws Exception {
		entity = null;
		if (id != null) {
			List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
			User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
			checkDataAuth(user, filters);
			filterRelevanceModul(filters);
			changeEntityName();
			gsMngManager.setUser(user);
			gsMngManager.setEntityName(entityName);
			TableEntity te = TableEntityCache.getInstance().get(entityName);
			if(te.getIsReferCommon()) {
				entity = gsMngManager.findEntityByHql(id, findType, filters, pager);
			} else {
				entity = gsMngManager.findEntity(id, findType, filters, pager);
			}
			/*if(null!=entity) {
				//过滤子列表属性
				if(null!=te && null!=te.getSubEntitys() && !te.getSubEntitys().isEmpty()) {
					List<String> filterProp = Lists.newArrayList();
					for(TableEntity t : te.getSubEntitys()) {
						filterProp.add(t.getRefSubEntityName());
					}
					preHandleObject(entity, filterProp);
				}
			}*/
		}
		formatMessage.setMsg(entity);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}	
	
	
	public String viewSub() throws Exception {
		// TODO Auto-generated method stub
		return VIEW_SUB;
	}
	
	/**
	 * 更新实体附件字段
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String updateAttach() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		gsMngManager.updateColumn(id, field, attachId);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	} 
	
	/**
	 * 更新实体某一指定字段
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String updateTableField() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		PropertyFilter pf = new PropertyFilter(field, value);
		gsMngManager.updateColumn(ids, pf.getPropertyName(), pf.getMatchValue());
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	/**
	 * 数据权限过滤，增加过滤条件
	 * 
	 * @param user
	 * @param filters
	 */
	private void checkDataAuth(User user, List<PropertyFilter> filters) {
		Boolean userAuthFlag = true;
		List<String> dataAuthList = user.getDataAuthList();
		PropertyFilter idPf = null;
		if(null!=dataAuthList && !dataAuthList.isEmpty()) {
			String authKey1 = Constants.RESOURCE_ALL_DATA_VISIBLE + Constants.UNDERLINE + entityName;
			if(dataAuthList.contains(authKey1)) { //所有数据可见
				userAuthFlag = false;
			} else {
				//判断共享数据可见权限
				String dataShareKey = Constants.RESOURCE_SHARE_USER_VISIBLE + Constants.UNDERLINE + entityName;
				if(dataAuthList.contains(dataShareKey)) {//共享数据可见
					List<String> entityIdList = dataShareConfigManager.find(entityName, user.getId());
					if(null!=entityIdList && !entityIdList.isEmpty()) {
						idPf = new PropertyFilter("INL_" + GsMngManager.ID, StringUtils.join(entityIdList, ","));
					}
				}
				//判断组织内数据可见
				String authKey = Constants.RESOURCE_DATA_IN_ORG + Constants.UNDERLINE + entityName;
				if(dataAuthList.contains(authKey)) { //组织内数据可见
					//获取同部门下所有用户
					List<Long> userIdList = accountManager.findUserInSameOrg(user.getOrgCode());
					PropertyFilter pf = new PropertyFilter("INL_" + GsMngManager.CREATE_USER, StringUtils.join(userIdList, ","));
					addShareUserFilter(pf, user, filters);
					if(idPf != null) {
						pf.addOrPropertyFilter(idPf);
					}
					filters.add(pf);
					userAuthFlag = false;
				}
			}
		} 
		if(userAuthFlag) {
			//默认个人可见
			PropertyFilter pf = new PropertyFilter("EQL_" + GsMngManager.CREATE_USER, String.valueOf(user.getId()));
			addShareUserFilter(pf, user, filters);
			if(idPf != null) {
				pf.addOrPropertyFilter(idPf);
			}
			filters.add(pf);
		}
	}
	
	/**
	 * 根据当前用户获取用户参数
	 * 
	 * @param user
	 * @return
	 */
	private Map<String, String> getUserParam(User user) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("$curUserId$", String.valueOf(user.getId()));
		param.put("$curUserLoginName$", user.getLoginName());
		param.put("$curOrgId$", user.getOrganizationId());
		param.put("$curOrgName$", user.getOrganizationName());
		param.put("$curOrgCode$", user.getOrgCode());
		param.put("$curUserEmployeeId$", user.getEmployeeId());
		param.put("$curUserName$", user.getNickname());
		return param;
	}
	
	/**
	 * 预处理字段条件属性，替换系统变量属性
	 * 
	 * @param val
	 * @param param
	 * @return
	 */
	private String preHandleFieldCond(String val, Map<String, String> param) {
		String result = val;
		for(Map.Entry<String, String> en : param.entrySet()) {
			result = StringUtils.replace(result, en.getKey(), en.getValue());
		}
		return result;
	}
	
	/**
	 * 预处理条件值，可以通过sql语句获取值
	 * 
	 * @param val
	 * @param user
	 * @return
	 */
	private String preHandleFieldSqlKey(Object val, User user) {
		String strVal = String.valueOf(val);
		if(StringUtils.startsWith(strVal, "$$")) {//$$sqlKey表示通过sqlkey获取属性值
			String sqlKey = StringUtils.substring(strVal, 2);
			List<Map<String,Object>> list = gsMngManager.queryList(sqlKey, new ArrayList<PropertyFilter>(), false, null, Integer.MAX_VALUE, true);
			List<Object> idList = new ArrayList<Object>();
			if(list != null && !list.isEmpty()) {
				for(Map<String, Object> map : list) {
					Object idVal = map.get("key");
					idList.add(idVal);
				}
			}
			if(idList.isEmpty()) {
				idList.add(0);
			}
			strVal = StringUtils.join(idList, ",");
		}
		return strVal;
	}
	
	/**
	 * 添加共享用户字段条件与可见用户条件
	 * 
	 * @param pf
	 * @param user
	 */
	@SuppressWarnings("unchecked")
	private void addShareUserFilter(PropertyFilter pf, User user, List<PropertyFilter> filters) {
		gsMngManager.setUser(user);
		//判断满足字段条件可见，条件应该是交集与
		//String authFieldKey = Constants.RESOURCE_FIELD_COND_VISIBLE + Constants.UNDERLINE + entityName;
		List<String> fcList = user.getFieldCondList(this.moduleName);
		if(null!=fcList && !fcList.isEmpty()) {
			List<PropertyFilter> andFilters = new ArrayList<PropertyFilter>();
			List<PropertyFilter> orFilters = new ArrayList<PropertyFilter>();
			Map<String, String> param = getUserParam(user);
			for(String fc : fcList) {
				if(StringUtils.isNotBlank(fc)) {
					Map<String, Object> map = jsonBinder.fromJson(preHandleFieldCond(fc, param), HashMap.class);
					if(null!=map) {
						for(Map.Entry<String, Object> en : map.entrySet()) {
							if(StringUtils.startsWithIgnoreCase(en.getKey(), "and_")) {
								//存在and_关键字开始，表示与所有者条件或关系
								PropertyFilter tmpPf = new PropertyFilter(en.getKey().substring(4), preHandleFieldSqlKey(en.getValue(), user));
								andFilters.add(tmpPf);
							} else { //默认or条件
								PropertyFilter tmpPf = new PropertyFilter(en.getKey(), preHandleFieldSqlKey(en.getValue(), user));
								orFilters.add(tmpPf);
							}
						}
					}
				}
			}
			filters.addAll(andFilters);//与条件处理
			if(!orFilters.isEmpty()) {//或条件处理
				for(PropertyFilter p : orFilters) {
					pf.addOrPropertyFilter(p);
				}
			}
		}
		//添加共享用户
		List<TeAttr> taList = TableEntityCache.getInstance().getUseAsShareUserAttrMap(entityName);
		if(null!=taList && !taList.isEmpty()) { 
			for(TeAttr ta : taList) {
				PropertyFilter p = new PropertyFilter("EQ" + ta.getShortTypeByType() + "_" + ta.getName(), String.valueOf(user.getId()));
				pf.addOrPropertyFilter(p);
			}
		}
		//添加可见用户和用户属性
		Map<String,List<Long>> seeUserMap = user.getSeeUserIdList(this.moduleName);
		if(null!=seeUserMap && !seeUserMap.isEmpty()) {
			for(Map.Entry<String, List<Long>> en : seeUserMap.entrySet()) {
				String attr = en.getKey();
				List<Long> seeUserIds = en.getValue();
				if(null!=seeUserIds && !seeUserIds.isEmpty()) {
					if(StringUtils.isNotBlank(attr)) {//可见用户属性
						PropertyFilter p = new PropertyFilter(attr, StringUtils.join(seeUserIds, ","));
						pf.addOrPropertyFilter(p);
					} else { //默认创建用户（所有者）
						PropertyFilter p = new PropertyFilter("INL_" + GsMngManager.CREATE_USER, StringUtils.join(seeUserIds, ","));
						pf.addOrPropertyFilter(p);
					}
				}
			}
		}
		//添加权限控制字段属性，与字段数据源权限一致
		List<TeAttr> afList = TableEntityCache.getInstance().getUseAsAuthFieldAttrMap(entityName);
		if(null!=afList && !afList.isEmpty()) { 
			for(TeAttr ta : afList) {
				String dsSqlKey = ta.getQueryEditSqlKey();//编辑数据源权限控制
				if(StringUtils.isNotBlank(dsSqlKey)) {
					List<String> resList = gsMngManager.findKeyListBySqlKey(dsSqlKey, true);
					if(null!=resList && !resList.isEmpty()) {
						String results = StringUtils.join(resList, ",");
						PropertyFilter p = new PropertyFilter("IN" + ta.getShortTypeByType() + "_" + ta.getName(), results);
						pf.addOrPropertyFilter(p);
					}
				}
			}
		}
		
		/*List<Long> seeUserIds = user.getSeeUserIdList(this.moduleName);
		//添加可见用户
		if(null!=seeUserIds && !seeUserIds.isEmpty()) {
			PropertyFilter p = new PropertyFilter("INL_" + GsMngManager.CREATE_USER, StringUtils.join(seeUserIds, ","));
			pf.addOrPropertyFilter(p);
		}*/
	}
	
	/**
	 * 业务字典请求
	 * 
	 * @return
	 * @throws Exception
	 */
	public String viewDicts() throws Exception {
		return DICTS;
	}
	
	/**
	 * 唯一性校验
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkUnique() throws Exception {
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		if(null!=id) {
			PropertyFilter pf = new PropertyFilter("NEL_" + GsMngManager.ID, String.valueOf(id));
			filters.add(pf);
		}
		//过滤子列表属性
		TableEntity te = TableEntityCache.getInstance().get(entityName);
		if(null!=te && !te.getIsSubEntity()) { //主表需要检测状态，子表不需要
			//增加作废状态的过滤，排除作废状态单据
			PropertyFilter pf = new PropertyFilter("NES_" + GsMngManager.STATUS, GsMngManager.STATUS_CANCEL);
			filters.add(pf);
		}
		//子表检查唯一性过滤主表记录
		if(null!=te && te.getIsSubEntity()) {
			String masterId = Struts2Utils.getParameter("masterId");
			if(StringUtils.isNotBlank(masterId)) {
				PropertyFilter pf = new PropertyFilter("NEL_" + te.getRefEntityName() + ".id", masterId);
				filters.add(pf);
			}
		}
		List<Map<String, Object>> list = gsMngManager.findList(filters);
		formatMessage.setMsg(list.isEmpty());
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 唯一性校验
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkUniqueV2() throws Exception {
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		if(null!=id) {
			PropertyFilter pf = new PropertyFilter("NEL_" + GsMngManager.ID, String.valueOf(id));
			filters.add(pf);
		}
		//过滤子列表属性
		TableEntity te = TableEntityCache.getInstance().get(entityName);
		if(null!=te && !te.getIsSubEntity()) { //主表需要检测状态，子表不需要
			//增加作废状态的过滤，排除作废状态单据
			PropertyFilter pf = new PropertyFilter("NES_" + GsMngManager.STATUS, GsMngManager.STATUS_CANCEL);
			filters.add(pf);
		}
		//子表检查唯一性过滤主表记录
		if(null!=te && te.getIsSubEntity()) {
			String masterId = Struts2Utils.getParameter("masterId");
			if(StringUtils.isNotBlank(masterId)) {
				PropertyFilter pf = new PropertyFilter("NEL_" + te.getRefEntityName() + ".id", masterId);
				filters.add(pf);
			}
		}
		List<Map<String, Object>> list = gsMngManager.findList(filters);
		//formatMessage.setMsg(list.isEmpty());
		ValidateMsg vm = new ValidateMsg();
		if(!list.isEmpty()) {
			vm.setValid(false);
			vm.setMessage("已存在重复值");
		}
		Struts2Utils.renderJson(vm);
		return null;
	}

	/**
	 * 唯一性校验
	 *
	 * @return
	 * @throws Exception
	 */
	public String checkUniqueV3() throws Exception {
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		List<PropertyFilter> propertyFilters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		ValidateMsg vm = new ValidateMsg();
		for(PropertyFilter propertyFilter :propertyFilters ) {
			List<PropertyFilter>  filters=new ArrayList<PropertyFilter>(){
				{
					add(propertyFilter);
				}
			};

			if (null != id) {
				PropertyFilter pf = new PropertyFilter("NEL_" + GsMngManager.ID, String.valueOf(id));
				filters.add(pf);
			}
			//过滤子列表属性
			TableEntity te = TableEntityCache.getInstance().get(entityName);
			if (null != te && !te.getIsSubEntity()) { //主表需要检测状态，子表不需要
				//增加作废状态的过滤，排除作废状态单据
				PropertyFilter pf = new PropertyFilter("NES_" + GsMngManager.STATUS, GsMngManager.STATUS_CANCEL);
				filters.add(pf);
			}
			//子表检查唯一性过滤主表记录
			if (null != te && te.getIsSubEntity()) {
				String masterId = Struts2Utils.getParameter("masterId");
				if (StringUtils.isNotBlank(masterId)) {
					PropertyFilter pf = new PropertyFilter("NEL_" + te.getRefEntityName() + ".id", masterId);
					filters.add(pf);
				}
			}
			List<Map<String, Object>> list = gsMngManager.findList(filters);
			//formatMessage.setMsg(list.isEmpty());
			if (!list.isEmpty()) {
				vm.setValid(false);
				vm.setFieldKey(propertyFilter.getPropertyName());
				vm.setMessage(propertyFilter.getMatchValue()+"已存在重复值");
				break;
			}
		}
		formatMessage.setMsg(vm);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 保存消息回填的字段数据
	 */
	@JsonOutput
	public String saveFieldsData() throws Exception {
		User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		Map<String, Object> map = ServletUtils.getParametersStartingWith(Struts2Utils.getRequest(), "notice_");	
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		gsMngManager.setUser(user);
		gsMngManager.updateMoreColumn(id,map);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	/**
	 * 发送消息通知
	 */
	@JsonOutput
	public String sendMessage() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		Map<String, Object> mapSend = jsonBinder.fromJson(jsonSenddata, HashMap.class);
		mapSend.put("style", style);
		gsMngManager.sendAllMessage(mapSend);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	/**
	 * 数据过滤
	 */
	@JsonOutput
	public String dataFilter() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		List<PropertyFilter> dynamicFilters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest(), "dynamic");
		Map<String, Object> map = gsMngManager.getFilterResult(entityName, filters,appendFlag, dynamicFilters);
		formatMessage.setMsg(map);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 分页数据过滤
	 */
	@JsonOutput
	public String dataFilterPage() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		List<PropertyFilter> dynamicFilters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest(), "dynamic");
		pager = gsMngManager.getFilterResult(entityName, filters,appendFlag, dynamicFilters, pager);
		Struts2Utils.renderJson(pager);
		return null;
	}
	
	/**
	 * 根据sqlkey获取sql显示字段列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String getFieldsBySqlKey() throws Exception {
		formatMessage.setMsg(gsMngManager.getFieldsBySqlKey(entityName));
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	/**
	 * 跳转到数据过滤页面
	 */
	public String dataFilterWin() throws Exception {
		return "win";
	}
	/**
	 * 跳转到自定义选择发送用户窗口
	 */
	public  String selUserWin()throws Exception {
		return "usersWin";
	}
	/**
	 * 选择数据填充
	 */
	public  String setDataWin()throws Exception {
		return "dataWin";
	}
	/**
	 * 创建存储过程
	 */
	@JsonOutput
	public String createProcedure() throws Exception {
		procManager.createProcedure(procContent);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 调用存储过程
	 */
	@JsonOutput
	public String callProcedure() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequestIncludeEmpty(Struts2Utils.getRequest());
		procManager.callProcedure(procKey,filters);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 调用存储过程返回值
	 */
	@JsonOutput
	public String callProcedureWithResult() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequestIncludeEmpty(Struts2Utils.getRequest());
		String result = procManager.callProcedureWithResult(procKey,filters);
		formatMessage.setMsg(result);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 更新多个实体的创建人
	 */
	@JsonOutput
	public String updateCreateUser() throws Exception {
		changeEntityName();
		gsMngManager.updateCreateUser(entityName,entityIds,field,value);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 导出模板
	 */
	public String outputExcelModule() throws Exception {
		String fileName = TableEntityCache.getInstance().getModuleName(this.moduleName) + "-数据模板.xls";
		String filePath = gsMngManager.getExcelTemplateFilePath(this.moduleName);
		Struts2Utils.writeFile(fileName, filePath, false);
		return null;
	}
	
	/**
	 * 导出Excel模块数据，分为部分导出与全部导出
	 */
	public String exportModuleExcel() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		List<PropertyFilter> fixFilters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest(), "fix");
		changeEntityName();
		TableEntity te = TableEntityCache.getInstance().get(entityName);
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		if(!ModuleProperties.TYPE_FORM.equalsIgnoreCase(te.getModuleType())) {	
			checkDataAuth(user, filters);
		}
		gsMngManager.setEntityName(entityName);
		gsMngManager.setUser(user);
		String filePath = gsMngManager.exportModuleData(value, pager, filters, fixFilters);
		String fileName = TableEntityCache.getInstance().getModuleName(this.moduleName) + ".xls";
		Struts2Utils.writeFile(fileName, filePath, false);
		return null;
	}
	
	/**
	 * 导入模板数据
	 */
	@JsonOutput
	public String importModuleExcel() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		String msg = gsMngManager.importModuleData(filedata);
		formatMessage.setMsg(msg);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 导入模板数据，支持二进制文件流上传
	 */
	@JsonOutput
	public String importModuleExcelV2() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		changeEntityName();
		gsMngManager.setEntityName(entityName);
		String filePackage = systemParam.getUploadPicPath()
				+ com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_PATH;
		String filePath = com.qyxx.platform.gsc.utils.Constants.UPLOADFILE_TEMP + 
					"importExcel" + com.qyxx.platform.gsc.utils.Constants.PATH_SEPARATOR + DateFormatUtils.format(System.currentTimeMillis(),
							"yyyyMMddHHmmssSSS");
		File destFile = new File(filePackage + filePath);
		InputStream inputStream = ServletActionContext.getRequest().getInputStream();
        FileUtils.copyInputStreamToFile(inputStream, destFile);
		String msg = gsMngManager.importModuleData(destFile);
		formatMessage.setMsg(msg);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	
	/**
	 * 导出异常数据Excel
	 */
	public String outputExpExcel() throws Exception {
		String fileName = TableEntityCache.getInstance().getModuleName(this.moduleName) + "-异常数据.xls";
		String filePath = gsMngManager.getExcelExportFilePath(value);
		Struts2Utils.writeFile(fileName, filePath, false);
		return null;
	}
	
	public String importFile() throws Exception {
		return "file";
	}
	
	/**
	 * 执行sql语句
	 */
	@JsonOutput
	public String execSql() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequestIncludeEmpty(Struts2Utils.getRequest(),"filter");
		int result = gsMngManager.execSql(entityName, filters);
		formatMessage.setMsg(result);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 执行批量sql语句
	 */
	@JsonOutput
	public String execBatchSql() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		List<Object> paramList = jsonBinder.fromJson(jsonSenddata, ArrayList.class);
		int result = gsMngManager.execBatchSql(paramList);
		formatMessage.setMsg(result);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	public String openFormView() throws Exception {
		operMethod = CrudActionSupport.VIEW;
		return GsMngAction.FORMS;
	}
	
	/**
	 * 打开JS文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String loadJs() throws Exception {
		String jsFile = Struts2Utils.getParameter("jf");
		return jsFile;
	}
	
	/**
	 * 批量修改数据
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@JsonOutput
	public String revise() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		Map<String, Object> map = jsonBinder.fromJson(jsonSaveData, HashMap.class);
		gsMngManager.setUser(user);
		Map<String, Object> result = gsMngManager.revise(map);
		formatMessage.setMsg(result);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	/**
	 * 根据word模板+sql查询数据导出分页的word文档
	 *
	 * @return
	 */
	public String exportWord() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		Map<String, Object> paramMap = jsonBinder.fromJson(jsonSenddata, HashMap.class);
		File file = gsMngManager.exportWord(paramMap);
		String fileName = DateFormatUtils.format(System.currentTimeMillis(),"yyyyMMddHHmmssSSS") + ".docx";
		Struts2Utils.writeFile(fileName, file.getAbsolutePath(), false);
		return null;
	}

	/**
	 * 根据word模板+sql查询数据导出分页的word文档
	 * 同步操作
	 * @return
	 */
	public String exportWordByTemplate() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		Map<String, Object> paramMap = jsonBinder.fromJson(jsonSenddata, HashMap.class);
		File file = gsMngManager.exportWordByTemplate(paramMap);
		String fileName = DateFormatUtils.format(System.currentTimeMillis(),"yyyyMMddHHmmssSSS") + ".docx";
		Struts2Utils.writeFile(fileName, file.getAbsolutePath(), false);
		return null;
	}

	/**
	 * 根据word模板+sql查询数据导出分页的word文档
	 * 异步操作
	 * @return
	 */
	@JsonOutput
	public String exportWordByTemplateAsync() throws Exception {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		gsMngManager.setUser(user);
		Map<String, Object> paramMap = jsonBinder.fromJson(jsonSenddata, HashMap.class);
		boolean flag = gsMngManager.exportWordByTemplateAsync(paramMap);
		formatMessage.setMsg(flag);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	public static void main(String[] args) {
		/*Map<String, Object> obj1 = new HashMap<String, Object>();
		obj1.put("itemSubject", "222");
		obj1.put("itemDescp", "adfadf");
		obj1.put("createtime", new Date());
		
		
		Map<String, Object> subObj = new HashMap<String, Object>();
		subObj.put("subject", "sdfasdf");
		subObj.put("addCol", "adfadf111f111");
		subObj.put("createtime", new Date());
		//subObj.put("mainEntity", obj1);
		
		
		Map<String, Object> subObj1 = new HashMap<String, Object>();
		subObj1.put("subject", "2222sdfasdf");
		subObj1.put("addCol", "2222adfadf111f111");
		subObj1.put("createtime", new Date());
		//subObj1.put("mainEntity", obj1);
		
		List<Map<String, Object>> subObjList = new ArrayList<Map<String, Object>>();
		subObjList.add(subObj);
		subObjList.add(subObj1);
		obj1.put("subEntitys", subObjList);
		
		List<Map<String, Object>> mainObjList = new ArrayList<Map<String, Object>>();
		mainObjList.add(obj1);
		
		Page<Map<String, Object>> pager1 = new Page<Map<String, Object>>(10);
		pager1.setResult(mainObjList);
		
		Set<String> set = new HashSet<String>();
		set.add("createtime");
		
		String s1 = Struts2Utils.objectToJson(obj1, set);
		System.out.println(s1);*/
//		String json = "{\"contractNo\":\"23\",\"contractsDate\":\"2012-08-05\",\"customerNo\":\"\",\"shortName\":\"23\",\"custFullName\":\"23\",\"contractsSheets\":{\"inserted\":[{\"id\":\"\",\"checkField\":\"23\",\"radioField\":\"23\",\"productItem\":\"23\",\"quality\":\"23\",\"Remark\":\"23\"}],\"updated\":[],\"deleted\":[]}}";
//		Map<String, Object> map = JsonBinder.getAlwaysMapper().fromJson(json, HashMap.class);
//		for (Map.Entry<String, Object> entry : map.entrySet()) {
//			System.out.println(entry.getKey() + ":" + entry.getValue());
//			if(entry.getValue() instanceof Map) {
//				Map<String, Object> obj = (Map<String, Object>)entry.getValue();
//				for (Map.Entry<String, Object> en : obj.entrySet()) {
//					System.out.println("Map:" + en.getKey() + ":" + en.getValue());
//				}
//			}
//			if(entry.getValue() instanceof List) {
//				List<Object> obj = (List<Object>)entry.getValue();
//				for(Object o : obj) {
//					System.out.println("List：" + o);
//				}
//			}
//		}

			String  idStr = "1,2,3";
			String[] idArr = idStr.split(",");
			Long[]  ids = new Long[idArr.length] ;
			for( int i=0;i<idArr.length;i++ ){
				ids[i]=Long.parseLong(idArr[i])   ;
				System.out.println(ids[i]);
			}


	}

}
